﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Communication;
using Database;

namespace WCFService
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    class ServerCommunication : IServerCommunication
    {

        private static Dictionary<User, IClientCommunication> users = new Dictionary<User, IClientCommunication>();
        private LogicForumImp logicforumimp = new LogicForumImp();
        private static int guest_No = 1;
        public IClientCommunication CurrentCallback
        {
            get
            {
                return OperationContext.Current.GetCallbackChannel<IClientCommunication>();
            }
        }
        public ServiceHost host = null;

        public void InitServer()
        {
            using (ServiceHost host = new ServiceHost(
                typeof(ServerCommunication),
                new Uri("net.tcp://localhost:8000")))
            {
                host.AddServiceEndpoint(typeof(IServerCommunication),
                  new NetTcpBinding(),
                  "ISubscribe");

                try
                {
                    host.Open(new TimeSpan(1000));
                    //host.Abort();
                    if (logicforumimp == null)
                        logicforumimp = new LogicForumImp();
                    Console.WriteLine("Successfully opened port 8000.");
                    Console.ReadLine();
                    host.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }


        public void Login(string flag, string username, Byte[] password, int forumid)
        {//if flag == guest its guest
            //if flag ==login its regular login

            System.Text.UTF8Encoding UTFEncoder = new System.Text.UTF8Encoding();


            if (flag.Equals("guest"))
            {//if its guest
                Boolean flagres = logicforumimp.login(forumid, "guest" + guest_No, "");
                User user = new User("guest" + guest_No, "", "", "0", "");
                try
                {
                    CurrentCallback.ReceiveJoin(user, true, "succed guest login");
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
                guest_No++;
                IClientCommunication ic=this.CurrentCallback;
                users.Add(user, ic);
                try
                {
                    ic.ReceiveNotify("Logged in as a Guest");
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
                    
            }
            else
            {
                IClientCommunication ic = this.CurrentCallback;
                Boolean flagres = logicforumimp.login(forumid, username, UTFEncoder.GetString(password));
                if (flagres == true)
                {
                    User res = logicforumimp.getuser(forumid, username);
                    //IClientCommunication callback = this.GetUserCallBack(res());
                    try
                    {
                        CurrentCallback.ReceiveJoin(res, true, "succed login");
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }

                    users.Add(res, ic);
                    try
                    {
                        ic.ReceiveNotify("Logged in as " + username);
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }
                else
                {
                    try
                    {
                        ic.RecieveError("Wrong User name or Password");
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }
            }
        }

        public void Logout(User me,int forumid)
        {
            //Boolean flag    =   logicforumimp.logout(me, forumid);
            //change Ilya
            
            logicforumimp.logout(me, forumid);
            removeUser(me);
        }

        public void Register(string name, string last, string nick, string pass, string email,int forumid)
        {
            if (this.logicforumimp.isAllowedActionInForum(forumid))
                this.logicforumimp.sendRegisterCode(name, last, nick, pass, email, forumid);
            else ConfirmMailForRegister(name, last, nick, pass, email, forumid, email.GetHashCode().ToString());
        }


        public void ConfirmMailForRegister(string name, string last, string nick, string pass, string email, int forumid, string code)
        {
            if (this.logicforumimp.confirmCode(name, last, nick, pass, email, forumid, code))
            {

                this.CurrentCallback.RecieveCodeConfirm();
                //int password = int.Parse(pass);
                Boolean flag = logicforumimp.Register(forumid, nick, name, last, pass, email);
                if (flag == true)
                {//need to do login
                    User user = logicforumimp.getuser(forumid, nick);
                    System.Text.UTF8Encoding UTFEncoder = new System.Text.UTF8Encoding();
                    Byte[] encr = UTFEncoder.GetBytes(pass);
                    this.Login("login", nick, encr, forumid);
                    this.notifyForum(forumid, "Welcome our New member " + nick);
                }
            }
            else
            {
                try
                {
                    this.CurrentCallback.RecieveError("The code you entered is wrong!");
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
        }


        public void GetForum(Communication.ClientRequest req)
        {
            Forum forum = logicforumimp.getForum(req.getUser(), req.getForumId());
            IClientCommunication callback = this.GetUserCallBack(req.getUser());
            if (forum != null)
            {
                try
                {
                    callback.ReceiveForum(forum);
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
            else
            {
                try
                {
                    callback.RecieveError("The forum you asked for does not exist!");
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }

        }

        public void AddForum(User me, User forummanagername, string forum, int policy, List<string> badWords)
        {
            Boolean flag = logicforumimp.AddForum(me, forum,forummanagername, policy, badWords);//fix this!!!!!!!!!
        }

        //dont need
        public void EditForum(Communication.ClientRequest req)
        {
           
        }

        //dont need
        public void DeleteForum(Communication.ClientRequest req)
        {
         
        }

        public void GetSubForum(Communication.ClientRequest req)
        {
            SubForum sb= this.logicforumimp.getSubForum(req.getUser(), req.getForumId(), req.getSubForumId());
            IClientCommunication callback = this.GetUserCallBack(req.getUser());
            if (sb != null)
            {
                try
                {
                    callback.ReceiveSubForum(sb);
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
            else
            {
                //if dont have the permission to do it
                // callback.AutherizationError();
            }

        }

        public void AddSubForum(Communication.ClientRequest req)
        {
          int flag=this.logicforumimp.AddSubForum(req.getUser(),req.getForumId(),req.getTitle(),req.getUser().getUserName());
          switch (flag)
            {
                case 0:
                      this.notifyForum(req.getForumId(), "New Sub Forum was added : " + req.getTitle());
                      this.refreshLocals(req.getUser(), 1, req.getForumId());
                      break;
                case 1:
                      try
                      {
                          this.CurrentCallback.AutherizationError();
                      }
                      catch
                      {
                          Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                          Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                      }
                      break;
                case 2:
                      try
                      {
                          this.CurrentCallback.RecieveError("Your Message contains a word Forbidden in this forum");
                      }
                      catch
                      {
                          Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                          Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                      }
                      break;
            }
        }



        //dont need
        public void EditSubForum(Communication.ClientRequest req)
        {
            
        }

        public void DeleteSubForum(Communication.ClientRequest req)
        {
            if (!this.logicforumimp.isAllowedActionInForum(req.getForumId()))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                string title = this.logicforumimp.getSubForum(req.getUser(), req.getForumId(), req.getSubForumId()).getTitle();
                Boolean flag = logicforumimp.RemoveSubForum(req.getUser(), req.getForumId(), req.getSubForumId());
                if (flag == true)
                {
                    this.notifyForum(req.getForumId(), "Sub Forum \"" + title + "\" was deleted from the Forum");
                    this.refreshLocals(req.getUser(), 1, req.getForumId());
                }
                else
                {
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }
            }
           
        }

        public void GetThread(Communication.ClientRequest req)
        {
            Thread thread = this.logicforumimp.getThread(req.getUser(), req.getForumId(),req.getThreadId());
            IClientCommunication callback = this.GetUserCallBack(req.getUser());
            if (thread != null)
                try
                {
                    callback.ReceiveThread(thread);
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            else
            {
                //if dont have the permission to do it
                // callback.AutherizationError();
            }
        }

        public void AddThread(Communication.ClientRequest req)
        {
            int flag = logicforumimp.AddThread(req.getUser(), req.getForumId(),req.getTitle(), req.getContent());
            switch (flag)
            {
                case 0:
                    //this.CurrentCallback.ReceiveNotify("a new Thread was added");
                    this.notifyForum(req.getForumId(), "a new Thread was added to sub forum \"" + this.logicforumimp.getSubForum(req.getUser(), req.getForumId(), this.logicforumimp.getUserSub(req.getUser().getUserName(), req.getForumId())).getTitle() + "\"");
                    this.refreshLocals(req.getUser(), 2, req.getForumId());
                    break;
                case 1:
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                    break;
                case 2:
                    try
                    {
                        this.CurrentCallback.RecieveError("Your Message contains a word Forbidden in this forum");
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                    break;
            }

        }

        public void EditThread(Communication.ClientRequest req)
        {
            if (!this.logicforumimp.isAllowedActionInForum(req.getForumId()))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                int flag = logicforumimp.EditThread(req.getUser(), req.getForumId(), req.getThreadId(), req.getTitle(), req.getContent() + "(edited by " + req.getUser().getUserName() + ")");
                switch (flag)
                {
                    case 0:
                        //this.CurrentCallback.ReceiveNotify("the Thread was edited");
                        this.notifyForum(req.getForumId(), "a Thread was edited in sub forum \"" + this.logicforumimp.getSubForum(req.getUser(), req.getForumId(), this.logicforumimp.getUserSub(req.getUser().getUserName(), req.getForumId())).getTitle() + "\"");
                        this.refreshLocals(req.getUser(), 2, req.getForumId());
                        break;
                    case 1:
                        try
                        {
                            this.CurrentCallback.AutherizationError();
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                    case 2:
                        try
                        {
                            this.CurrentCallback.RecieveError("Your Message contains a word Forbidden in this forum");
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                }
            }
        }

        public void DeleteThread(Communication.ClientRequest req)
        {
            if (!this.logicforumimp.isAllowedActionInForum(req.getForumId()))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                Boolean flag = logicforumimp.RemoveThread(req.getUser(), req.getForumId(), req.getThreadId());
                if (flag == true)
                {
                    //this.CurrentCallback.ReceiveNotify("the Thread was deleted");
                    this.notifyForum(req.getForumId(), "a Thread was deleted from sub forum \"" + this.logicforumimp.getSubForum(req.getUser(), req.getForumId(), this.logicforumimp.getUserSub(req.getUser().getUserName(), req.getForumId())).getTitle() + "\"");
                    this.refreshLocals(req.getUser(), 2, req.getForumId());
                }
                else
                {
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }
            }
        }


        //no need to implement
        public void GetPost(Communication.ClientRequest req)
        {
            Post post = this.logicforumimp.getPost(req.getUser(), req.getForumId(), req.getSubForumId(), req.getThreadId(),req.getPostId());
            IClientCommunication callback = this.GetUserCallBack(req.getUser());
            if (post != null)
                return;//  callback.re(post);
            else
            {
                //if dont have the permission to do it
                // callback.AutherizationError();
            }
        }

        public void AddPost(Communication.ClientRequest req)
        {
            int flag = logicforumimp.AddPost(req.getUser(),req.getForumId(), req.getTitle(),req.getContent());
            switch (flag)
                {
                    case 0:
                        //this.CurrentCallback.ReceiveNotify("the Post was added");
                        this.notifyForum(req.getForumId(), "a new Post was added to Thread \"" + this.logicforumimp.getThread(req.getUser(),req.getForumId(),this.logicforumimp.getUserThread(req.getUser().getUserName(), req.getForumId())).getTitle()+ "\"");
                        this.refreshLocals(req.getUser(), 3, req.getForumId());
                        break;
                    case 1:
                        try
                        {
                            this.CurrentCallback.AutherizationError();
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                    case 2:
                        try
                        {
                            this.CurrentCallback.RecieveError("Your Message contains a word Forbidden in this forum");
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                }
        }

        public void EditPost(Communication.ClientRequest req)
        {
            if (!this.logicforumimp.isAllowedActionInForum(req.getForumId()))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                int flag = logicforumimp.EditPost(req.getUser(), req.getForumId(), req.getPostId(), req.getTitle(), req.getContent() + "(edited by " + req.getUser().getUserName() + ")");
                switch (flag)
                {
                    case 0:
                        //this.CurrentCallback.ReceiveNotify("the Post was edited");
                        this.notifyForum(req.getForumId(), "a new Post was edited in Thread \"" + this.logicforumimp.getThread(req.getUser(), req.getForumId(), this.logicforumimp.getUserThread(req.getUser().getUserName(), req.getForumId())).getTitle() + "\"");
                        this.refreshLocals(req.getUser(), 3, req.getForumId());
                        break;
                    case 1:
                        try
                        {
                            this.CurrentCallback.AutherizationError();
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                    case 2:
                        try
                        {
                            this.CurrentCallback.RecieveError("Your Message contains a word Forbidden in this forum");
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                        }
                        break;
                }
            }
        }

        public void DeletePost(Communication.ClientRequest req)
        {
            if (!this.logicforumimp.isAllowedActionInForum(req.getForumId()))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                Boolean flag = logicforumimp.RemovePost(req.getUser(), req.getForumId(), req.getPostId());
                if (flag == true)
                {
                    //this.CurrentCallback.ReceiveNotify("the Post was deleted");
                    this.notifyForum(req.getForumId(), "a Post was deleted from Thread \"" + this.logicforumimp.getThread(req.getUser(), req.getForumId(), this.logicforumimp.getUserThread(req.getUser().getUserName(), req.getForumId())).getTitle() + "\"");
                    this.refreshLocals(req.getUser(), 3, req.getForumId());
                }
                else
                {
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }

            }
        }

        public void AddModerator(User me, string moderatorname, string subforum,int forumid)
        {
            int subforumid=logicforumimp.getSubForumID(forumid,subforum);
            
            Boolean flag= logicforumimp.AddNewModeratorToSubForum(me,forumid,subforumid,moderatorname);
            if (flag == true)
                this.notifyForum(forumid, moderatorname + " was appointed to moderate " + subforum);
            else
            {
                try
                {
                    this.CurrentCallback.AutherizationError();
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }

        }

        public void DeleteModerator(User me, string moderatorname, string subforum,int forumid)
        {
            if (!this.logicforumimp.isAllowedActionInForum(forumid))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                int subforumid = logicforumimp.getSubForumID(forumid, subforum);
                Boolean flag = logicforumimp.RemoveModerator(me, forumid, subforumid, moderatorname);
                if (flag == true)
                    this.notifyForum(forumid, moderatorname + " was removed from moderating " + subforum);
                else
                {
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }
            }
        }

        public void ExchangeModerator(User me,string oldMod, string newMod, string subforum,int forumid)
        {
            if (!this.logicforumimp.isAllowedActionInForum(forumid))
                this.CurrentCallback.RecieveError("This action is Not supported in this forum!");
            else
            {
                int subforumid = logicforumimp.getSubForumID(forumid, subforum);
                Boolean flag = logicforumimp.ChangeTheSubForumModerator(me, forumid, subforumid, oldMod, newMod);
                if (flag == true)
                    this.notifyForum(forumid, newMod + " has taken moderating insted of " + oldMod + " in subforum " + subforum);
                else
                {
                    try
                    {
                        this.CurrentCallback.AutherizationError();
                    }
                    catch
                    {
                        Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                        Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                    }
                }

            }
        }

        //dont need AddForum(Common.DataBaseNew.User me, string name, string forum)
        

        //dont need
        public void DeleteManager(User me, string name, string forum)
        {
            
        }


        public void GetForumStatistics(User me, int forumID)
        {
            if (me.getUserName().Equals(logicforumimp.getdirector().getUserName())
                || me.getUserName().Equals(logicforumimp.getForum(me ,forumID).getAdmin().getUserName()))
            {
                string str="";
                str =str+ logicforumimp.getAllStatistic(me, forumID);
                IClientCommunication callback = this.GetUserCallBack(me);
                this.GetForum(new ClientRequest(me,forumID));
                try
                {
                    callback.ReceiveForumStatistics(str);
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
            else {
                try
                {
                    this.CurrentCallback.AutherizationError();
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
           
        }

        public void GetSystemStatistics(string admin, string adminPassword)
        {//the director doing it
            User director=logicforumimp.getdirector();
            if (director==null)
                return;
            IClientCommunication callback = this.GetUserCallBack(director);
            string str="the number of common users are : "+ logicforumimp.getNumberOfCommonUsers(director);
            str=str+"\r\n the number of forums:" +logicforumimp.getNumberOfForum(director)+" \r\n";
            //change Ilya
            //callback.ReceiveSystemStatistics(logicforumimp.getUserLists(),str);
            User user = logicforumimp.getdirector();
            if (callback == null)
            {
                IClientCommunication ic = this.CurrentCallback;
                users.Add(user, ic);
                try
                {
                    ic.ReceiveSystemStatistics(str, user);//this is a stab!!!!!!
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
            else
            {
                try
                {
                    callback.ReceiveSystemStatistics(str, user);//this is a stab!!!!!!
                }
                catch
                {
                    Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                    Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
                }
            }
            
            
        }

        public void getUserList()
        {//to implement this function
            throw new NotImplementedException();
        }





        public void getSystemUserList()
        {
            throw new NotImplementedException();
        }

        public void getForumUserList(User user, int forumID)
        {
            IClientCommunication callback = this.GetUserCallBack(user);
            try
            {
                callback.ReceiveForumUsersList(logicforumimp.getForumUsers(forumID).Values.ToList());
            }
            catch
            {
                Console.WriteLine("ERROR: tryied to communicate with a client that is no longer connected(and didn't logged out)");
                Logger.log("ERROR: tryied to communicate with  a client that is no longer connected(and didn't logged out)");
            }
        }

        public bool Subscribe()
        {
            throw new NotImplementedException();
        }


        public void AdminExit(User user)
        {
            users.Remove(user);
        }

        private IClientCommunication GetUserCallBack(User user)
        {
            if (users.ContainsValue(CurrentCallback))
            {
                foreach (User u in users.Keys)
                {
                    if (user.getUserName().Equals(u.getUserName()))
                    {
                        IClientCommunication userCallBack = users[u];
                        return userCallBack;
                        break;
                    }
                }
            }
            return null;
        }

        private void notifyForum(int forumId, string message)
        {
            SortedDictionary<string,User> forumUsers = this.logicforumimp.getForumUsers(forumId);
            foreach (User user in users.Keys)
                {
                foreach (User inForum in forumUsers.Values)
                    if(String.Equals(user.getUserName(),inForum.getUserName()))
                    {
                        IClientCommunication callback = this.GetUserCallBack(user);
                        try
                        {
                            callback.ReceiveNotify(message);
                        }
                        catch
                        {
                            Console.WriteLine("ERROR: tryied to notify a client that is no longer connected(and didn't logged out)");
                            Logger.log("ERROR: tryied to notify a client that is no longer connected(and didn't logged out)");
                        }
                    }
                }
        }

        private bool removeUser(User user)
        {
            foreach (User usr in users.Keys)
            {
                if (user.getUserName().Equals(usr.getUserName()))
                {
                    users.Remove(usr);
                    return true;
                    break;
                }
            }
            return false;
        }

        private void refreshLocals(User user, int level, int forum)//level: 1=forum : 2=subForum : 3=thread
        {
            int sub = this.logicforumimp.getUserSub(user.getUserName(), forum);
            int thread = this.logicforumimp.getUserThread(user.getUserName(), forum);
            

            switch (level){
                case 1:
                    Forum comForum = logicforumimp.getForum(user, forum);
                    foreach (User local in users.Keys.ToList())
                        if (this.logicforumimp.getUserSub(local.getUserName(), forum) == -1 && this.logicforumimp.getUserForum(local.getUserName(), forum) == forum)
                        {
                            try
                            {
                                GetUserCallBack(local).ReceiveForum(comForum);
                            }
                            catch
                            {
                                Console.WriteLine("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                                Logger.log("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                            }
                        }
                    break;
                case 2:
                    SubForum comSub = logicforumimp.getSubForum(user, forum, sub);
                    foreach (User local in users.Keys.ToList())
                        if (this.logicforumimp.getUserSub(local.getUserName(), forum) == sub && this.logicforumimp.getUserForum(local.getUserName(), forum) == forum && this.logicforumimp.getUserThread(local.getUserName(), forum) == -1)
                        {
                            try
                            {
                                GetUserCallBack(local).ReceiveSubForum(comSub);
                            }
                            catch
                            {
                                Console.WriteLine("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                                Logger.log("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                            }
                        }
                    break;
                case 3:
                    Thread comThraed = logicforumimp.getThread(user, forum, thread);
                    foreach (User local in users.Keys.ToList())
                        if (this.logicforumimp.getUserSub(local.getUserName(), forum) == sub && this.logicforumimp.getUserForum(local.getUserName(), forum) == forum && this.logicforumimp.getUserThread(local.getUserName(), forum) == thread)
                        {
                            try
                            {
                                GetUserCallBack(local).ReceiveThread(comThraed);
                            }
                            catch
                            {
                                Console.WriteLine("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                                Logger.log("ERROR: tryied to refresh a client that is no longer connected(and didn't logged out)");
                            }
                        }
                    break;
            }
        }

    }
}
